package com.oig.sys.workflow.oauth.impl;

import cn.hutool.core.date.DateUtil;
import com.oig.common.constants.CommonConstants;
import com.oig.oauth.api.OauthService;
import com.oig.sys.workflow.oauth.IDepOauthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Map;

@Component
@Slf4j
public class DepOauthServiceImpl implements IDepOauthService {

    private final OauthService oauthService;

    public DepOauthServiceImpl(OauthService oauthService){
        this.oauthService = oauthService;
    }

    @Value("${sys.oauth2.client-id}")
    private String clientId;
    @Value("${sys.oauth2.client-secret}")
    private String clientSecret;

    private String accessToken ;
    private Long expiresTimes=10L; //到期（秒）
    //private String refreshToken;

    /**
     * 使用客户端凭证模式处理，客户端凭证的 authorities 要配置接口权限
     */
    private String getNewAccessToken(){
        long req_sc = DateUtil.currentSeconds();   //系统秒
        MultiValueMap<String,Object> params = new LinkedMultiValueMap<>() ;
        params.add("grant_type","client_credentials") ;
        params.add("client_id", clientId) ;
        params.add("client_secret", clientSecret) ;
        Map<String,Object> rep = this.oauthService.token(params);
        int exp_sc = (int) rep.get("expires_in");    //有效秒数
        expiresTimes = req_sc + exp_sc - 60 ;    //到期秒
        return  (String)rep.get(CommonConstants.ACCESS_TOKEN) ;
    }

    //根据过期时间来判断
    private boolean checkAccessToken(){
        long now = DateUtil.currentSeconds();   //系统秒
        return (now < expiresTimes);
    }


    @Override
    public String getAccessToken() {
        if (accessToken==null){
            log.debug("get token");
            accessToken = this.getNewAccessToken();
        } else {
            log.debug("check_token:{}",accessToken);
            if (!checkAccessToken()){
                accessToken = this.getNewAccessToken();
            }
        }
        return accessToken;
    }

}
